package ybl.qianchuan;

import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import ybl.qianchuan.entities.LiveRoom;
import ybl.qianchuan.entities.OneDayLiveData;
import ybl.qianchuan.entities.QianchuanAweme;

public class AwemeManage {
    // 获取指定aweme正在直播的场次的GMV和花费
    public static LiveRoom getLivingRoomGMVandAdCost(String awemeId) {
        LiveRoom lRoom = new LiveRoom();
        List<QianchuanAweme> qianchuanAwemes = AccountManage.getQianchuanAwemesByawemeShowId(awemeId);
        if (qianchuanAwemes.isEmpty()) {
            return null;
        }

        JSONObject jsonObject = null;
        JSONArray rooms = null;
        // 查看近8天有无正在进行的直播
        for (int i = 0; i < 8; i++) {
            jsonObject = LiveDataManage.getRoomsByStartDay(
                    Auth.getAccessTokenByAccessTokenName(
                            qianchuanAwemes.get(0).getAccessTokenName()).getAccessToken(),
                    qianchuanAwemes.get(0).getQianchuanId(), qianchuanAwemes.get(0).getAwemeId(),
                    DateUtils.getBeforeDay(i),
                    "LIVING");
            // 处理千川接口返回的错误
            if (jsonObject.getIntValue("code") != 0) {
                if (jsonObject.getIntValue("code") != 40002) {
                    throw new ApiException(jsonObject.getString("message"));
                }
                switch (jsonObject.getIntValue("code")) {
                    case 40002:
                        // 删除该千川ID
                        AccountManage.deleteQianchuanAweme(qianchuanAwemes.get(0).getQianchuanId());
                        throw new ApiException(qianchuanAwemes.get(0).getQianchuanId()
                                + " no permissions currently. Deleted. Please try again!");
                    default:
                        throw new ApiException(
                                qianchuanAwemes.get(0).getQianchuanId() + jsonObject.getString("message"));
                }
            }

            rooms = jsonObject.getJSONObject("data").getJSONArray("room_list");
            if (!rooms.isEmpty()) { // 获取正在直播的场次，即跳出循环
                break;
            }
        }

        if (!rooms.isEmpty()) { // 存在正在进行的直播
            for (JSONObject room : rooms.toJavaList(JSONObject.class)) {
                lRoom.setAwemeId(room.getLong("aweme_id"));
                lRoom.setStartTime(room.getString("start_time"));
                lRoom.setRoomId(room.getLong("room_id"));
                lRoom.setGmv(room.getDoubleValue("live_pay_order_gmv_alias") / 1000);
                lRoom.plusCost(room.getDoubleValue("stat_cost") / 1000); // 单位为分
            }

            List<QianchuanAweme> awemeHasUniProms = AccountManage.getQianchuanAwemesAwemeHasUniProm(awemeId);
            if (awemeHasUniProms.isEmpty()) {
                // 标准投放
                qianchuanAwemes.subList(1, qianchuanAwemes.size()).forEach(qianchuanAweme -> {
                    JSONObject respJsonObject = LiveDataManage.getRoomsByStartDay(
                            Auth.getAccessTokenByAccessTokenName(qianchuanAweme.getAccessTokenName()).getAccessToken(),
                            qianchuanAweme.getQianchuanId(),
                            qianchuanAweme.getAwemeId(),
                            lRoom.getStartTime().substring(0, 10),
                            "LIVING");
                    if (respJsonObject.getInteger("code") != 0) {
                        throw new ApiException(respJsonObject.getString("message"));
                    }
                    JSONArray liveRooms = respJsonObject.getJSONObject("data").getJSONArray("room_list");
                    for (JSONObject room : liveRooms.toJavaList(JSONObject.class)) {
                        lRoom.setAwemeId(room.getLong("aweme_id"));
                        lRoom.setStartTime(room.getString("start_time"));
                        lRoom.setRoomId(room.getLong("room_id"));
                        lRoom.setGmv(room.getDoubleValue("live_pay_order_gmv_alias") / 1000);
                        lRoom.plusCost(room.getDoubleValue("stat_cost") / 1000); // 单位为分
                    }
                });
            } else {
                // 全域投放
                awemeHasUniProms.forEach(qianchuanAweme -> {
                    JSONObject uniPrObject = LiveDataManage.uniPromotion(
                            Auth.getAccessTokenByAccessTokenName(qianchuanAweme.getAccessTokenName()).getAccessToken(),
                            qianchuanAweme.getQianchuanId(),
                            qianchuanAweme.getAwemeId(),
                            lRoom.getStartTime(),
                            DateUtils.getNow());
                    lRoom.plusCost(uniPrObject.getJSONObject("data").getList("list", JSONObject.class).get(0)
                            .getDoubleValue("stat_cost") * 100); // 官方返回单位为元，此处换为单位为分
                    Double gmv = uniPrObject.getJSONObject("data").getList("list", JSONObject.class).get(0)
                            .getDoubleValue("total_pay_order_gmv_for_roi2");
                    if (gmv != 0) {
                        lRoom.setGmv(gmv * 100); // 官方返回单位为元，此处换为单位为分
                    }
                });
            }
        }
        lRoom.setAwemeShowId(awemeId);
        return lRoom;
    }

    public static OneDayLiveData getOneDayGmvByAweme(String awemeShowId, String oneDay) {
        List<QianchuanAweme> awemeHasUniProms = AccountManage.getQianchuanAwemesAwemeHasUniProm(awemeShowId);
        OneDayLiveData oneDayLiveData = new OneDayLiveData();
        oneDayLiveData.setAwemeShowId(awemeShowId);
        oneDayLiveData.setDay(oneDay);
        if (awemeHasUniProms.isEmpty()) {
            // 标准投放，使用获取今日推广报表 api
            AccountManage.getQianchuanAwemesByawemeShowId(awemeShowId).forEach(item -> {
                JSONObject respJsonObject = LiveDataManage.getOneDayLiveData(
                        Auth.getAccessTokenByAccessTokenName(item.getAccessTokenName()).getAccessToken(),
                        item.getQianchuanId(),
                        item.getAwemeId(),
                        oneDay);
                if (respJsonObject.getIntValue("code") == 0) {
                    Long gmv = respJsonObject.getJSONObject("data").getLongValue("live_pay_order_gmv_alias") / 1000; // 此时单位是末转为分（分
                                                                                                                     // 厘
                                                                                                                     // 毫
                                                                                                                     // 末）
                    Long cost = respJsonObject.getJSONObject("data").getLongValue("stat_cost") / 1000; // 此时单位是末转为分（分 厘
                                                                                                       // 毫 末）
                    if (gmv != 0) {
                        oneDayLiveData.setGmv(gmv);
                    }
                    oneDayLiveData.plusCost(cost);
                }
            });

        } else {
            // 全域投放，使用获取全域推广账户维度数据api
            awemeHasUniProms.forEach(item -> {
                JSONObject respJsonObject = LiveDataManage.uniPromotion(
                        Auth.getAccessTokenByAccessTokenName(item.getAccessTokenName()).getAccessToken(),
                        item.getQianchuanId(),
                        item.getAwemeId(),
                        oneDay + " 00:00:00",
                        oneDay + " 23:59:59");
                if (respJsonObject.getIntValue("code") == 0) {
                    Long gmv = respJsonObject.getJSONObject("data").getLongValue("total_pay_order_gmv_for_roi2") * 100; // 此时单位是元转为分
                    Long cost = respJsonObject.getJSONObject("data").getLongValue("stat_cost") * 100; // 此时单位是元转为分
                    oneDayLiveData.plusGmv(gmv);
                    oneDayLiveData.plusCost(cost);
                }
            });
        }
        return oneDayLiveData;
    }

    public static OneDayLiveData getTodayDataByAweme(String awemeShowId) {
        return getOneDayGmvByAweme(awemeShowId, DateUtils.getToday());
    }
}
